package com.yixing.tech.wcs;

import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;

public class ProducerConsumerDemo2 {

    public static final BlockingDeque<Integer> deque = new LinkedBlockingDeque<>(20);

    public static class Producer implements Runnable {
        private final BlockingDeque<Integer> deque;

        Producer(BlockingDeque<Integer> deque) {
            this.deque = deque;
        }

        @Override
        public void run() {
            try {
                for(int i=0;i<1200;++i) {
                    deque.putLast(i);
                    System.out.println("生产者生产: " + i);
                    Thread.sleep(20);
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
    }

    public static class Consumer implements Runnable {
        private final BlockingDeque<Integer> deque;

        Consumer(BlockingDeque<Integer> deque) {
            this.deque = deque;
        }

        @Override
        public void run() {
            try {
                while(true) {
                    for(int i=0;i<deque.size(); ++i) {
                        int value = deque.takeFirst();
                        System.out.println("消费者消费: " + value);
                    }
                    Thread.sleep(10);
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
    }

    public static void main(String... args) {
        Producer producer = new Producer(deque);
        Consumer consumer = new Consumer(deque);

        new Thread(producer).start();
        new Thread(consumer).start();
    }
}
